package com.dy.springcloud.service.impl;

import com.dy.springcloud.dao.OrderDao;
import com.dy.springcloud.entity.Order;
import com.dy.springcloud.service.AccountService;
import com.dy.springcloud.service.OrderService;
import com.dy.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;
    @Resource
    private StorageService storageService;
    @Resource
    private AccountService accountService;


    //使用实现分布式事务控制,name = "hsp-save-order" 指定名字
    //rollbackFor = Exception.class  发生Exception.class 则回滚
    @GlobalTransactional(name = "hsp-save-order",rollbackFor = Exception.class)
    @Override
    public void save(Order order) {
        log.info("=========开始新建订单 start ==========");
        log.info("=========生成订单 start ==========");
        orderDao.save(order);
        log.info("=========生成订单 end ==========");

        log.info("=========减少库存 start ==========");
        storageService.reduce(order.getProductId(),order.getNums());
        log.info("=========减少库存 end ==========");

        log.info("=========减少money start ==========");
        accountService.result(order.getUserId(),order.getMoney());
        log.info("=========减少money end ==========");

        log.info("=========修改订单 start ==========");
        orderDao.update(order.getUserId(),0);
        log.info("=========修改订单 end ==========");

        log.info("=========开始新建订单 end ==========");
    }
}
